package demo.iterator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class UserFile implements Iterable<User> {

    private final File file;

    public UserFile(File file) {
        this.file = file;
    }

    @Override
    public Iterator<User> iterator() {
        return new UserItr();
    }

    public class UserItr implements Iterator<User> {
        private BufferedReader reader;
        private User nextUser;
        private boolean finished = false;

        public UserItr() {
            try {
                reader = new BufferedReader(new FileReader(file));
                advance(); // 预先读取第一行
            } catch (IOException e) {
                closeReader();
                throw new RuntimeException("Failed to initialize iterator", e);
            }
        }

        private void advance() {
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (!line.isEmpty()) {
                        String[] split = line.split(",");
                        if (split.length == 2) {
                            nextUser = new User(split[0], Integer.parseInt(split[1]));
                            return;
                        }
                    }
                }
                // 文件读取完毕
                nextUser = null;
                finished = true;
                closeReader();
            } catch (IOException e) {
                closeReader();
                throw new RuntimeException("Failed to read line", e);
            } catch (NumberFormatException e) {
                closeReader();
                throw new RuntimeException("Invalid age format", e);
            }
        }

        @Override
        public boolean hasNext() {
            return !finished;
        }

        @Override
        public User next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            User current = nextUser;
            advance(); // 读取下一行
            return current;
        }

        private void closeReader() {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                // 静默关闭，或者记录日志
            }
        }
    }
}